import React, { useEffect, useState } from "react";
import {
  Card,
  Avatar,
  Tag,
  Descriptions,
  Row,
  Col,
  Spin,
  Form,
  Input,
  Button,
  Modal,
  message,
} from "antd";
import axios from "axios";
import service from "@/http/request";

const UserCenter = () => {
  const [user, setUser] = useState(null);
  const [infoModalVisible, setInfoModalVisible] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [editLoading, setEditLoading] = useState(false);
  const [shareRatio, setShareRatio] = useState(0.8);
  const [remainingDownloadCount, setRemainingDownloadCount] = useState(1);
  const [connectionStatus, setConnectionStatus] = useState("用户已连接");
  const [uploadTotal, setUploadTotal] = useState(0);
  const [downloadTotal, setDownloadTotal] = useState(0);

  function bytesToMB(bytes) {
    return bytes / (1024 * 1024);
  }
  
  useEffect(() => {
    fetchUser();
  }, []);

  const fetchUser = async () => {
    const res1 = await service.get("/users/info");

    setUser(res1);

    const res2 = await service.get("/users/my-rewarded-ratio");
    setShareRatio(res2.shareRatio);
    setUploadTotal(bytesToMB(res2.uploadTotal).toFixed(2));
    setDownloadTotal(bytesToMB(res2.downloadTotal).toFixed(2));

    const res3 = await service.get("/users/downloads/remaining");
    setRemainingDownloadCount(res3);

    const res4 = await service.get("/users/my-status");
    if (res4) {
      setConnectionStatus("用户已连接");
      message.success("用户已连接");
    } else {
      setConnectionStatus("用户未连接");
      message.error("用户未连接");
    }
  };

  const handleUpdateInfo = (values) => {
    setEditLoading(true);
    axios
      .post("/api/user/update", values)
      .then(() => {
        message.success("信息更新成功！");
        fetchUser();
        setInfoModalVisible(false);
      })
      .catch(() => message.error("信息更新失败"))
      .finally(() => setEditLoading(false));
  };

  const handleUpdatePassword = (values) => {
    if (values.newPassword !== values.confirmPassword) {
      message.warning("两次输入的新密码不一致！");
      return;
    }
    axios
      .put(
        "http://127.0.0.1:4523/m1/6367429-6063635-973503d5/users/changePassword",
        {
          username: "111",
          oldPassword: values.oldPassword,
          newPassword: values.newPassword,
        }
      )
      .then(() => {
        message.success("密码修改成功！");
        setPasswordModalVisible(false);
        passwordForm.resetFields();
      })
      .catch(() => message.error("密码修改失败"));
  };

  if (!user) {
    return <Spin style={{ display: "block", margin: "100px auto" }} />;
  }

  return (
    <Card
      style={{ maxWidth: 700, margin: "40px auto" }}
      title="用户中心"
      variant={false}
    >
      <Row gutter={16} align="middle">
        <Col>
          <Avatar
            size={80}
            src={`https://api.dicebear.com/7.x/bottts-neutral/svg?seed=${user.username}`}
            style={{
              border: `3px solid ${user.nicknameColor}`,
              backgroundColor: "#f0f0f0",
            }}
          />
        </Col>
        <Col>
          <h2 style={{ margin: 0 }}>
            {user.username}{" "}
            <span style={{ color: user.nicknameColor }}>
              {user.title === "欧皇" ? "（欧皇）" : ""}
            </span>
          </h2>
          <Tag color="blue">{user.role}</Tag>
        </Col>
      </Row>

      <Descriptions column={1} style={{ marginTop: 24 }} bordered size="middle">
        <Descriptions.Item label="等级">{user.level}</Descriptions.Item>
        <Descriptions.Item label="虚拟比率">
          {user.virtualRatio.toFixed(2)}
        </Descriptions.Item>
        <Descriptions.Item label="积分">{user.credit}</Descriptions.Item>
        <Descriptions.Item label="状态">{user.status}</Descriptions.Item>
        <Descriptions.Item label="上传次数">
          {user.uploadCount}
        </Descriptions.Item>
        <Descriptions.Item label="下载次数">
          {user.downloadCount}
        </Descriptions.Item>
        <Descriptions.Item label="注册时间">
          {new Date(user.createdAt).toLocaleString()}
        </Descriptions.Item>
        <Descriptions.Item label="上传总量">{`${uploadTotal} MB`}</Descriptions.Item>
        <Descriptions.Item label="下载总量">{`${downloadTotal} MB`}</Descriptions.Item>
        <Descriptions.Item label="分享率">{shareRatio}</Descriptions.Item>

        <Descriptions.Item label="剩余下载次数">
          {remainingDownloadCount}
        </Descriptions.Item>
        <Descriptions.Item label="用户连接性">
          {connectionStatus}
        </Descriptions.Item>
      </Descriptions>

      <div style={{ textAlign: "center", marginTop: 24 }}>
        <Button type="primary" onClick={() => setInfoModalVisible(true)}>
          修改信息
        </Button>
        <Button
          style={{ marginLeft: 12 }}
          onClick={() => setPasswordModalVisible(true)}
        >
          修改密码
        </Button>
      </div>

      {/* 修改信息弹窗 */}
      <Modal
        title="修改信息"
        open={infoModalVisible}
        onCancel={() => setInfoModalVisible(false)}
        onOk={() => form.submit()}
        confirmLoading={editLoading}
      >
        <Form form={form} layout="vertical" onFinish={handleUpdateInfo}>
          <Form.Item label="用户名" name="username">
            <Input />
          </Form.Item>
          <Form.Item label="邮箱" name="email">
            <Input />
          </Form.Item>
          <Form.Item label="头衔" name="title">
            <Input />
          </Form.Item>
          <Form.Item label="昵称颜色（十六进制）" name="nicknameColor">
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改密码弹窗 */}
      <Modal
        title="修改密码"
        open={passwordModalVisible}
        onCancel={() => setPasswordModalVisible(false)}
        onOk={() => passwordForm.submit()}
      >
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handleUpdatePassword}
        >
          <Form.Item
            label="旧密码"
            name="oldPassword"
            rules={[{ required: true, message: "请输入旧密码" }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[{ required: true, message: "请输入新密码" }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="确认新密码"
            name="confirmPassword"
            rules={[{ required: true, message: "请再次输入新密码" }]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default UserCenter;
